package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.entity.UserPaidPost;
import com.isoft.c2team3service2.mapper.UserPaidPostMapper;
import com.isoft.c2team3service2.service.PostService;
import com.isoft.c2team3service2.service.UserPaidPostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserPaidPostServiceImpl extends ServiceImpl<UserPaidPostMapper, UserPaidPost> implements UserPaidPostService {
    private static final Logger log = LoggerFactory.getLogger(UserPaidPostServiceImpl.class);
    @Autowired
    private PostService postService;


    @Override
    @Transactional
    public boolean purchasePost(Integer userId, Integer postId) {
        // 1. 校验帖子是否为付费帖子
        Post post = postService.getById(postId);
        if (post == null || post.getIsPaid() != 1) {
            return false; // 非付费帖子或不存在
        }

        // 2. 校验是否已购买（防止重复支付）
        if (hasPaid(userId, postId)) {
            return true; // 已购买直接返回成功
        }

        // 3. 创建购买记录
        UserPaidPost paidRecord = new UserPaidPost();
        paidRecord.setUserId(userId);
        paidRecord.setPostId(postId);
        paidRecord.setPayAmount(post.getPrice()); // 支付金额与帖子价格一致
        paidRecord.setPayTime(LocalDateTime.now());

        return save(paidRecord);
    }
    @Override
    // UserPaidPostServiceImpl
    public boolean hasPaid(Integer userId, Integer postId) {
        LambdaQueryWrapper<UserPaidPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidPost::getUserId, userId)
                .eq(UserPaidPost::getPostId, postId);
        return count(queryWrapper) > 0;
    }
}